
import org.junit.Test;

import java.io.*;

/**
 * JDK7之前的文件拷贝功能
 */
public class FileCopyTest {
    /**
     * 1. 创建输入/输出流
     * 2. 执行文件拷贝。读取文件内容，写入到另一个文件中
     * 3. 关闭文件流资源
     */
    @Test
    public void copyFile() {
        String originalUrl = "test/FileCopyTest.java";
        String targetUrl = "test/target.txt";

        FileInputStream originalFileInputStream = null;
        FileOutputStream targetFileOutputStream = null;

        try {
            originalFileInputStream = new FileInputStream(originalUrl);
            targetFileOutputStream = new FileOutputStream(targetUrl);

            // 读取的字节
            int content;

            // 迭代，读取/写入字节
            while ((content = originalFileInputStream.read()) != -1) {
                targetFileOutputStream.write(content);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (targetFileOutputStream != null) {
                try {
                    targetFileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (originalFileInputStream != null) {
                try {
                    originalFileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
